﻿using System.Collections.Generic;
using System.Windows;
using OAuth.Providers.ETrade;
using OAuth.Providers.ETrade.Model;

namespace OAuth.Samples.ETrade
{

    public partial class MainWindow
    {

        #region Accounts

        public IEnumerable<Account> Accounts
        {
            get { return (IEnumerable<Account>)GetValue(AccountsProperty); }
            set { SetValue(AccountsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Accounts.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AccountsProperty =
            DependencyProperty.Register("Accounts", typeof(IEnumerable<Account>), typeof(MainWindow), new UIPropertyMetadata(null));

        #endregion

        #region Quotes

        public IEnumerable<Quote> Quotes
        {
            get { return (IEnumerable<Quote>)GetValue(QuotesProperty); }
            set { SetValue(QuotesProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Quotes.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty QuotesProperty =
            DependencyProperty.Register("Quotes", typeof(IEnumerable<Quote>), typeof(MainWindow), new UIPropertyMetadata(null));

        #endregion

        private readonly Identity _identity;

        public MainWindow()
        {
            InitializeComponent();
            _identity = new Identity();
            Loaded += MainWindowLoaded;
        }

        private void MainWindowLoaded(object sender, RoutedEventArgs e)
        {
            FrmLoginWeb frm = new FrmLoginWeb(_identity);
            frm.Owner = this;
            var result = frm.ShowDialog();

            if (result.HasValue && result.Value)
            {
                LoadAccountList();
                LoadQuotes();
            }
            else
                Application.Current.Shutdown();
        }

        private void LoadAccountList()
        {
            Accounts accounts = new Accounts(_identity.AccessToken);
            accounts.GetAccountListCompleted += (values) => { Accounts = values; };
            accounts.GetAccountList();
        }

        private void LoadQuotes()
        {
            Market market = new Market(_identity.AccessToken);
            market.GetQuotesCompleted += (quotes) => Quotes = quotes;
            market.GetQuotes("MSFT", "AAPL");
        }

    }

}